﻿using Borg;
using System;
using UILibrary;

public class ConsoleUC : ShellControl
{
    private readonly WriteDelegate _writeDelegate;

    public new event CommandEventHandler CommandEntered;

    public ConsoleUC()
    {
        _writeDelegate = Write;
    }

    protected override void OnCommandEntered(string command)
    {
        if (CommandEntered != null)
            CommandEntered(this, new CommandEventArgs(command));
    }

    private void Write(string text, bool newline)
    {
        if (IsDisposed)
            return;

        if (InvokeRequired)
            Invoke(_writeDelegate, new object[] {text, newline});
        else
        {
            WriteText(text);
            
            if (newline)
            {
                WriteText(Environment.NewLine);
                PrintPrompt();
            }

            if (!Focused)
                Focus();
        }
    }

    public void Write(string text, params object[] args)
    {
        Write(string.Format(text, args), false);
    }

    public void WriteLine(string text, params object[] args)
    {
        Write(string.Format(text, args), true);
    }

    private delegate void WriteDelegate(string text, bool newline);
}

